package com.hunter.jerrymouse.response.netty;

import com.hunter.jerrymouse.response.Response;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

/**
 * Created by hunter
 * <p>
 * netty的响应实现类
 */
public class NettyResponse implements Response {

    /**
     * 持有的管道上下文
     */
    private ChannelHandlerContext channelHandlerContext;

    /**
     * 持有的响应体
     */
    private FullHttpResponse response;

    public NettyResponse(ChannelHandlerContext channelHandlerContext) {
        this.channelHandlerContext = channelHandlerContext;
        this.response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());
    }

    @Override
    public void setContentType(String contentType) {
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }

    @Override
    public void setContentLength(int contentLength) {
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, contentLength);
    }

    @Override
    public void addHeader(String headerName, String headerValue) {
        response.headers().set(headerName, headerValue);
    }

    @Override
    public void write(byte[] bytes) {
        response.content().writeBytes(bytes);
    }

    @Override
    public void write(byte[] bytes, int begin, int end) {
        response.content().writeBytes(bytes, begin, end);
    }

    @Override
    public void flush() {
        channelHandlerContext.writeAndFlush(response);
    }

    @Override
    public void close() {
        channelHandlerContext.close();
    }
}
